<script setup lang="ts">
import { request } from '@/api'
import { onMounted, ref } from 'vue'
// 修复 b64-to-blob 的导入
import b64toBlob from 'b64-to-blob';
import { showConfirmDialog, showLoadingToast, showToast } from 'vant'
import type { ActionSheetAction } from 'vant'

// 获取用户信息
// const user = jk.getUser()
const user = ref<myuserRes>({} as myuserRes)
onMounted(async () => {
  const res = await request.get<JkResponse<myuserRes>>('/v1_0/user/profile')
  user.value = res.data.data
  //生日列表和弹窗中数据保存一致
  currentDate.value = user.value.birthday.split('-')

  console.log('用户信息', JSON.stringify(res.data))
})
//-------头像模块------
const actions = ref([{ name: '拍照' }, { name: '本地选择' }])
const showAvatarSheet = ref(false)
const onSelect = async (action: ActionSheetAction, index: number) => {
  console.log(index)
  try {
    if (index === 0) {
      const res = await jk.Camera()
      updateAvatar(res)
      // console.log(res)
    }
    if (index === 1) {
      const res = await jk.getPhoto()
      updateAvatar(res)
    }
  } catch (e) {
    console.error('捕获到错误:', e);
    showToast('取消选择');
  }
}
//修改头像
const updateAvatar = async (data: string) => {
  const img = b64toBlob(data, 'image/jpeg')
  //创建一个formData实例
  const formData = new FormData()
  // 追加
  formData.append('photo', img, Date.now() + '.jpeg')
  //开启加载弹窗
  const showLoad = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  })
  //发送请求
  const res = await request<JkResponse<updatePhotoRes>>({
    url: '/v1_0/user/photo',
    method: 'PATCH',
    data: formData,
  })
  console.log('请求接口后的地址:' + JSON.stringify(res))
  user.value.photo = res.data.data.photo
  showLoad.close()
  //更新鸿蒙端
  const userInfo = jk.getUser()
  userInfo.photo = res.data.data.photo
  //更新用户信息
  jk.setUser(userInfo)
}
//------性别模块------
const sex = ref([{ name: '男' }, { name: '女' }])
const showSexSheet = ref(false)
const onSexSelect = (action: ActionSheetAction, index: number) => {
  console.log(action, index)
  if (index === 0) {
    user.value.gender = 0
  } else {
    user.value.gender = 1
  }
}

//生日模块
const showBottom = ref(false)
const currentDate = ref(['2002', '05', '08']);
const minDate = ref(new Date(1970, 0, 1))
const maxDate = ref(new Date(2025, 5, 1))

const onDateSelect = () => {
  user.value.birthday = currentDate.value.join('-')
  showBottom.value = false
}

//修改用户信息
const updateInfo = async () => {
  const res = await request<JkResponse<editUserRes>, editUserReq>({
    url: '/v1_0/user/profile',
    method: 'PATCH',
    data: user.value
  })
  console.log('修改数据', JSON.stringify(res));
  showToast('修改成功')

  setTimeout(() => {
    jk.toBack()
  }, 2000);

}

//退出登录
const logout = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '亲,您确定要退出吗?'
  })
    .then(() => {
      // on confirm
      jk.clearUser()
      jk.clearPreference()
      //返回至登录页
      jk.toLogin()


    })
    .catch(() => {
      // on cancel
      console.log('用户取消退出');
    });
};

</script>
<template>
  <van-cell-group>
    <!-- 头像 -->
    <van-cell title="头像" @click="showAvatarSheet = true" is-link>
      <van-image round width="50px" height="50px" :src="user.photo" />
    </van-cell>
    <!-- 点击展示底部弹窗组件 -->
    <van-action-sheet v-model:show="showAvatarSheet" :actions="actions" cancel-text="取消" close-on-click-action
      @cancel="showAvatarSheet = false" @select="onSelect" />
    <!-- 昵称 -->
    <van-field label="昵称" placeholder="请输入昵称" v-model="user.name" is-link />

    <!-- 简介 -->
    <van-field label="简介" placeholder="请输入简介" v-model="user.intro" is-link />

    <!-- 性别 -->
    <van-cell title="性别" @click="showSexSheet = true" :value="user.gender == 1 ? '女' : '男'" is-link />
    <!-- 点击展示底部弹窗组件 -->
    <van-action-sheet v-model:show="showSexSheet" :actions="sex" cancel-text="取消" close-on-click-action
      @cancel="showSexSheet = false" @select="onSexSelect" />
    <!-- 生日 -->
    <van-cell title="生日" @click="showBottom = true" :value="user.birthday" is-link />
    <!-- 底部日历弹窗 -->
    <!-- 底部弹出 -->
    <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '45%' }">
      <van-date-picker v-model="currentDate" title="选择日期" :min-date="minDate" :max-date="maxDate"
        @cancel="showBottom = false" @confirm="onDateSelect" />
    </van-popup>

    <!-- 退出登录按钮 -->
    <van-button type="primary" @click="updateInfo" block class="logout-btn">修改信息</van-button>
    <van-button type="danger" @click="logout" block class="logout-btn">退出登录</van-button>
  </van-cell-group>
</template>

<style scoped>
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.van-cell {
  padding: 16px 12px;
  margin-bottom: 4px;
}

.text {
  text-align: right;
  width: 100%;
}

.logout-btn {
  margin-top: 24px;
  border-radius: 8px;
  height: 48px;
  font-size: 16px;
}

.van-cell-group {
  margin: 12px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
}
</style>
